int vA,vB,vC,vD;                //定义4个电机的速度变量
int dA,dB,dC,dD;                //电机旋转方向
int dir;                        //小车运动方向

void setup() 
{
  pinMode(2, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  Serial.begin(9600);
}

void loop() 
{
  if(Serial.available()>0)        //查询串口
  {
    dir = Serial.read();          //将串口接收的赋给运动方向变数据量
  }

  switch(dir)
  {
    case 0x00:                   //停
    dA = LOW;vA = 0;
    dB = LOW;vB = 0;
    dC = LOW;vC = 0;
    dD = LOW;vD = 0;
    break;

    case 0x02 :               //前进
    dA = HIGH;vA = 100;
    dB = HIGH;vB = 100;
    dC = LOW;vC = 100;
    dD = LOW;vD = 100;
    break;

    case 0x08:                   //后退
    dA = LOW;vA = 150;
    dB = LOW;vB = 150;
    dC = HIGH;vC = 150;
    dD = HIGH;vD = 150;         
    break;

    case 0x01:                  //前进左转
    dA = LOW;vA = 0;
    dB = HIGH;vB = 100;
    dC = HIGH;vC = 100;
    dD = LOW;vD = 100;
    break; 

    case 0x03:                   //前进右转
    dA = HIGH;vA = 100;
    dB = LOW;vB = 0;
    dC = LOW;vC = 100;
    dD = HIGH;vD = 100;
    break;

    case 0x10:                   //全速前进
    dA = HIGH;vA = 0;
    dB = HIGH;vB = 0;
    dC = HIGH;vC = 0;
    dD = HIGH;vD = 0;
    break;

    case 0x12:                  //全速后退
    dA = LOW;vA = 255;
    dB = LOW;vB = 255;
    dC = LOW;vC = 255;
    dD = LOW;vD = 255;
    break;

    case 0x04:
    dA = HIGH;vA = 100;
    dB = HIGH;vB = 100;
    dC = HIGH;vC = 100;
    dD = LOW;vD = 100;
    break;
    case 0x06:
    dA = LOW;vA = 100;
    dB = LOW;vB = 100;
    dC = LOW;vC = 100;
    dD = HIGH;vD = 100;
     break;
    

   
  }
   
  digitalWrite(2, dA);          //执行
  analogWrite(3,vA);
  digitalWrite(4, dB);
  analogWrite(5,vB);
  digitalWrite(7, dC);
  analogWrite(6,vC); 
  digitalWrite(8, dD);
  analogWrite(9,vD);
}
